<template>
  <div class="home">
    <!--轮播图-->
    <div class="header">
      <div class="name">{{ userInfo ? userInfo.kdusername : '' }}，欢迎您~</div>
      <div class="currentCenter" @click="handleSelect()">
        <div class="txt">当前登录：</div>
        <div class="txt1">
          {{ fixCenterName ? fixCenterName : '请选择' }}
          <i class="iconfont icon-right"></i>
        </div>
      </div>
      <!-- <van-field
        class="currentCenter"
        v-model="fixCenterName"
        name="当前登录"
        label="当前登录:"
        input-align="right"
        placeholder="请选择"
        right-icon="arrow"
        @click="handleSelect()"
        readonly
      /> -->

      <!-- 下拉选择弹窗 -->
      <van-popup v-model="showSelectPicker" position="bottom">
        <van-field
          name="模糊查询"
          input-align="left"
          v-model="likeWho"
          label="模糊查询"
          placeholder="请输入模糊查询关键词"
        />
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="handleSelectConfirm"
          @cancel="showSelectPicker = false"
          value-key="name"
        />
      </van-popup>
    </div>
    <!-- 任务中心 -->
    <div class="content_task">
      <div class="taskbox" @click="goTaskCenter">
        <div class="task_name">
          任务中心
          <img
            class="icon_index_back"
            src="@/assets/images/icon_index_back.png"
          />
        </div>
        <img class="icon_task" src="@/assets/images/icon_task.png" />
      </div>
      <div class="today_right">
        <div class="today_item item_add">
          <div class="today_name">今日新增</div>
          <div class="today_num num_add">{{ todaySum }}</div>
          <img class="icon_add" src="@/assets/images/icon_add.png" />
        </div>
        <div class="today_item item_over">
          <div class="today_name">今日跟进</div>
          <div class="today_num num_over">{{ todayFollowSum }}</div>
          <img class="icon_over" src="@/assets/images/icon_over.png" />
        </div>
      </div>
    </div>

    <!-- 菜单 -->
    <div class="menu">
      <div
        class="menu_item"
        v-for="(item, index) in menuList"
        :key="index"
        @click="goRouter(item)"
      >
        <div class="menu_itembox">
          <i :class="`iconfont ${item.icon}`"></i>
        </div>
        <div class="menu_name">{{ item.name }}</div>
      </div>
    </div>

    <!-- 数据 -->
    <div class="chartData">
      <div class="charTab">
        <div
          class="charTab_item"
          @click="handleTabChange(index)"
          :class="tabIndex == index ? 'active' : ''"
          v-for="(item, index) in timeList"
          :key="index"
        >
          {{ item.name }}
        </div>
      </div>
      <div class="chartDatabox">
        <div class="chart_num">任务数量趋势</div>
        <div id="container"></div>
      </div>
      <div class="chartDatabox">
        <div class="chart_num">任务跟进及时率</div>
        <div id="pie1"></div>
      </div>
      <div class="chartDatabox">
        <div class="chart_num">任务类型分布</div>
        <div id="pie2"></div>
      </div>
      <!-- <div class="chartPiebox">
        <div class="chartPie">
          <div class="chart_num">任务跟进及时率</div>
          <div id="pie1"></div>
        </div>
        <div class="chartPie">
          <div class="chart_num">任务类型分布</div>
          <div id="pie2"></div>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Picker } from 'vant'
import homeApi from '@/api/homeApi'
import commonApi from '@/api/commonApi'
import taskApi from '@/api/taskApi'
import { getCookies, getFieldName } from '@/utils/util.js'

export default {
  data() {
    return {
      images: [],
      lists: null,
      bannerLists: null,
      isWaterfallDisabled: false,
      loading: false,
      nodata: 1,
      pageNum: 1,
      pageSize: 6,
      userInfo: {},
      columns: [],
      value1: 1,
      menuList: [
        { icon: 'icon-dj', name: '外服登记', url: '/registerList' },
        { icon: 'icon-yy', name: '维修预约', url: '/applyRepair' },
        { icon: 'icon-case', name: '车辆档案', url: '/carOrder' },
        { icon: 'icon-gd', name: '维修工单', url: '/repairOrder' },
        { icon: 'icon-jqr', name: '保单机器人', url: '/policyRobot' },
        { icon: 'icon-sj', name: '数据统计', url: 'taskData' },
      ],
      timeList: [
        { name: '本周', code: 'week' },
        { name: '本月', code: 'month' },
        { name: '本年', code: 'year' },
      ],
      tabIndex: 0,
      userId: getCookies('userId'),
      fixCenterList: [],
      fixCenterName: '',
      fixCenterId: '',
      showSelectPicker: false,
      userInfo: JSON.parse(getCookies('userInfo')),
      todaySum: 0,
      todayFollowSum: 0,
      pieData1: [],
      pieData2: [],
      taskRate: [],
      likeWho: '',
      columns: [],
    }
  },

  mounted() {
    this.getUserInfo()
  },
  watch: {
    fixCenterId: {
      handler: function (val, oldVal) {
        if (val) {
          localStorage.setItem('orgId', this.fixCenterId)
          if (this.userId && this.fixCenterId) {
            this.getTaskDataByPerson()
            this.getTaskAddAndFollowCount()
          }
        }
      },
      deep: true,
      immediate: false,
    },
    likeWho: function (nval, oval) {
      if (nval) {
        let newArr = this.fixCenterList.filter((item) => {
          return item.name.indexOf(nval) > -1
        })
        console.log(newArr)
        this.columns = newArr
      } else {
        this.columns = this.fixCenterList
      }
    },
  },

  methods: {
    getUserInfo() {
      homeApi.getUseInfo({}).then((res) => {
        localStorage.setItem('userId', res.kduserid)
        localStorage.setItem('userInfo', JSON.stringify(res))
        this.userInfo = res
        this.userId = res.kduserid
        this.getMainFixCenter()
      })
    },
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          orgId: 'test',
          userId: this.userId,
          type: '',
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data
            if (localStorage.getItem('orgId')) {
              this.fixCenterId = localStorage.getItem('orgId')
              this.fixCenterName = getFieldName(
                res.data,
                'billId',
                this.fixCenterId,
              )
            } else {
              this.fixCenterId = res.data[0].billId
              this.fixCenterName = res.data[0].name
              localStorage.setItem('orgId', this.fixCenterId)
            }
          }
        })
    },
    getTaskDataByPerson() {
      taskApi
        .getTaskDataByPerson({
          countType: 'person',
          personId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data
            this.fixCenterId = res.data[0].billId
            this.fixCenterName = res.data[0].name
            localStorage.setItem('orgId', this.fixCenterId)
          }
        })
    },
    getTaskAddAndFollowCount() {
      taskApi
        .getTaskAddAndFollowCount({
          timeType: this.timeList[this.tabIndex].code,
        })
        .then((res) => {
          if (res) {
            // 新增
            let entryJaAddObj = this.formmatEcharData(res.entryJaAdd)
            let entryJaFollowObj = this.formmatEcharData(res.entryJaFollow)

            // let todayFollowObj = this.formmatEcharData(res.todayFollow)
            // let todayAddObj = this.formmatEcharData(res.entryJaAdd)
            // this.todayAddX = Object.keys(todayAddObj)
            // this.todayAddY = Object.values(todayAddObj)
            // this.todayFollowX = Object.keys(todayFollowObj)
            // this.todayFollowY = Object.values(todayFollowObj)

            // 新增任务数
            this.entryJaAddX = Object.keys(entryJaAddObj)
            this.entryJaAddY = Object.values(entryJaAddObj)
            // 跟进任务数
            this.entryJaFollowX = Object.keys(entryJaFollowObj)
            this.entryJaFollowY = Object.values(entryJaFollowObj)
            // 任务处理率
            this.taskRate = []
            this.entryJaAddX.forEach((item, index) => {
              this.entryJaFollowX.forEach((el, i) => {
                if (item == el) {
                  if (
                    this.entryJaAddY[index] != 0 &&
                    this.entryJaFollowY[i] != 0
                  ) {
                    this.taskRate.push(
                      (
                        (this.entryJaFollowY[i] / this.entryJaAddY[index]) *
                        100
                      ).toFixed(2),
                    )
                  }
                } else {
                  this.taskRate.push(0)
                }
              })
            })
            let todayAddKey = null
            let todayFollowKey = null
            if (res.todayAdd.length != 0) {
              for (const key in res.todayAdd[0]) {
                todayAddKey = key
              }
              this.todaySum = res.todayAdd[0][todayAddKey]
            }
            if (res.todayFollow.length != 0) {
              for (const key in res.todayFollow[0]) {
                todayFollowKey = key
              }
              this.todayFollowSum = res.todayFollow[0][todayFollowKey]
            }

            this.pieData1 = [
              { name: '及时跟进', value: res.bingFollowNotExpeed },
              { name: '逾期跟进', value: res.bingFollowExpeed },
            ]
            let data2 = []
            if (res.bingTaskType && res.bingTaskType.length != 0) {
              res.bingTaskType.forEach((item) => {
                data2.push({
                  name: item.taskName,
                  value: item.nums,
                })
              })
            }
            this.pieData2 = data2

            this.drawBarChart()
            this.drawPieChart1()
            this.drawPieChart2()
          }
        })
    },

    formmatEcharData(data) {
      if (data && data.length != 0) {
        let obj = data.reduce((e, item) => ({ ...e, ...item }), {})
        return obj
      }
      return {}
    },

    goRouter(data) {
      this.$router.push(data.url)
    },
    drawBarChart() {
      let echart = this.$echarts.init(document.getElementById('container'))
      let option = {
        legend: { data: ['新增任务数', '跟进任务数', '任务处理率'] },
        xAxis: { data: this.entryJaAddX },
        tooltip: {
          show: true,
          trigger: 'item',
        },
        yAxis: {},
        grid: {
          top: '18%',
          left: '15%', //原来是10%，修改为20%
          right: '2%',
          bottom: '24%',
        },

        series: [
          {
            name: '新增任务数',
            type: 'bar',
            data: this.entryJaAddY,
            itemStyle: {
              normal: {
                color: '#4590ff', // 设置柱子的颜色
              },
            },
            // barWidth: '10',
          },

          {
            name: '跟进任务数',
            type: 'bar',
            data: this.entryJaFollowY,
            itemStyle: {
              normal: {
                color: '#99c2ff', // 设置柱子的颜色
              },
            },
            // barWidth: 30,
          },

          {
            name: '任务处理率',
            type: 'line',
            data: this.taskRate,
            lineStyle: {
              color: '#ff9904',
            },
          },
        ],
      }
      echart.setOption(option)
      window.onreset = () => {
        echart.resize()
      }
    },
    drawPieChart1() {
      let echart = this.$echarts.init(document.getElementById('pie1'))
      let option = {
        legend: {
          orient: 'vertical',
          left: 'left',
        },
        tooltip: {
          show: true,
          trigger: 'item',
        },
        grid: {
          top: '18%',
          left: '20%', //原来是10%，修改为20%
          right: '2%',
          bottom: '24%',
        },
        series: [
          {
            // name: "及时跟进",
            type: 'pie',
            radius: '50%',
            data: this.pieData1,
            //   label: {
            //   normal: {
            //     position: 'inside',
            //       show: true,
            //     formatter: '{c}'
            //   }
            // }
          },
        ],
      }
      echart.setOption(option)
      window.onreset = () => {
        echart.resize()
      }
    },
    drawPieChart2() {
      let echart = this.$echarts.init(document.getElementById('pie2'))
      let option = {
        legend: {
          orient: 'center',
          left: 'left',
        },
        tooltip: {
          show: true,
          trigger: 'item',
        },
        grid: {
          top: '20%',
          left: '20%', //原来是10%，修改为20%
          right: '2%',
          bottom: '0',
        },
        series: [
          {
            // name: "及时跟进",
            type: 'pie',
            radius: '50%',
            data: this.pieData2,
            // [
            // { name: "定期保养", value: 10 },
            // { name: "质保到期", value: 30 },
            // { name: "质保延保", value: 30 },
            // { name: "保养套餐到期", value: 30 },
            // ],
            // label: {
            //   normal: {
            //     position: 'inside',
            //     show: true,
            //     formatter: '{b}:{c}'
            //   }
            // }
            // labelLine: {
            //   show: false, //隐藏指示线
            // },
            // label: {
            //   show: false, //隐藏标示文字
            // },
          },
        ],
      }
      echart.setOption(option)
      window.onreset = () => {
        echart.resize()
      }
    },
    handleTabChange(index) {
      this.tabIndex = index
      this.getTaskAddAndFollowCount()
    },
    goTaskCenter() {
      this.$router.push('/taskCenter')
    },

    handleSelect() {
      this.showSelectPicker = true
      this.columns = this.fixCenterList
    },
    handleSelectConfirm(value) {
      this.fixCenterId = value.billId
      this.fixCenterName = value.name
      this.showSelectPicker = false
      this.likeWho = ''
    },
  },
}
</script>

<style lang="less" scoped="">
@font-face {
  font-family: 'iconfont'; /* Project id 4176972 */
  src: url('//at.alicdn.com/t/c/font_4176972_s8s6zd59eop.woff2?t=1689868658391')
      format('woff2'),
    url('//at.alicdn.com/t/c/font_4176972_s8s6zd59eop.woff?t=1689868658391')
      format('woff'),
    url('//at.alicdn.com/t/c/font_4176972_s8s6zd59eop.ttf?t=1689868658391')
      format('truetype');
}
body {
  background: #f3f3f3;
}
.home {
  background: #f3f3f3;
  padding-bottom: 0.2rem;
}
#container {
  width: 90%;
  height: 300px;
  margin: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 1rem;
  padding: 0 0.25rem;
  .name {
    font-size: 0.3rem;
  }
  .selectbox {
    width: 3.5rem;
    background: none;
  }
  .currentCenter {
    display: flex;
    align-items: center;
    .txt {
      font-size: 0.26rem;
      color: #666;
    }
    .txt1 {
      font-size: 0.3rem;
      .iconfont {
        font-size: 0.3rem;
        color: #666;
      }
    }
  }
}
.content_task {
  display: flex;
  justify-content: space-between;
  padding: 0.25rem;
  background: #fff;
  margin: 0 0.2rem;
  border-radius: 10px;
  margin-bottom: 0.2rem;
  .taskbox {
    background: #f6f2ff;
    height: 3rem;
    width: 49%;
    border-radius: 10px;
    position: relative;
    .task_name {
      padding-top: 0.4rem;
      color: #444;
      padding-left: 0.4rem;
      font-size: 0.4rem;
      display: flex;
      align-content: center;

      .icon_index_back {
        width: 0.4rem;
      }
    }
    .icon_task {
      width: 1.1rem;
      position: absolute;
      bottom: 0.3rem;
      right: 0.4rem;
    }
  }
  .today_right {
    width: 48%;
    .today_item {
      height: 1.4rem;
      margin-bottom: 0.2rem;
      border-radius: 10px;
      position: relative;
      .today_name {
        padding-top: 0.2rem;
        color: #444;
        font-size: 0.32rem;
        padding-left: 0.2rem;
      }
      .today_num {
        text-align: right;
        margin-right: 1rem;
        margin-top: 0.1rem;
        font-weight: bold;
        font-size: 0.5rem;
      }
      .num_add {
        color: #ff9600;
      }
      .num_over {
        color: #00be63;
      }
      .icon_add {
        width: 0.6rem;
        position: absolute;
        bottom: 0.25rem;
        right: 0.2rem;
      }
      .icon_over {
        width: 0.7rem;
        position: absolute;
        bottom: 0.2rem;
        right: 0.1rem;
      }
    }
    .item_add {
      background: #dff3ed;
    }
    .item_over {
      background: #e2f4ff;
    }
  }
}
.menu {
  padding: 0.25rem 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background: #fff;
  margin: 0 0.25rem;
  border-radius: 10px;
  .menu_item {
    width: 25%;
    text-align: center;
    align-items: center;
    align-self: center;
    margin-bottom: 0.2rem;
    .menu_itembox {
      height: 1rem;
      width: 1rem;
      background: #f3f3f3;
      border-radius: 50%;
      margin: auto;
      margin-bottom: 0.2rem;
    }
    .iconfont {
      font-size: 0.54rem;
      margin-bottom: 0.3rem;
      display: block;
      line-height: 1rem;
      color: #011778;
    }
    .menu_name {
      font-size: 0.28rem;
    }
    &:nth-child(n + 5) {
      margin-bottom: 0;
    }
  }
}
.chartData {
  background: #fff;
  margin: 0 0.25rem;
  border-radius: 10px;
  margin-top: 0.25rem;
  padding-top: 0.4rem;
  margin-bottom: 0.2rem;
  .charTab {
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
    width: 3.6rem;
    margin: auto;
    border-radius: 5px;
    overflow: hidden;
    border: 1px solid #0383eb;

    .charTab_item {
      width: 33.33%;
      padding: 0.13rem 0.2rem;
      color: #0383eb;
      border-right: 1px solid #0383eb;
      text-align: center;
      font-size: 0.26rem;
      &.active {
        background: #0383eb;
        color: #fff;
      }
      &:last-child {
        border: none;
      }
    }
  }
  .chart_num {
    font-size: 0.3rem;
    text-align: center;
    margin-top: 0.3rem;
    margin-bottom: 0.2rem;
    text-align: center;
  }
  .chartPiebox {
    display: flex;
    .chartPie {
      width: 50%;
    }
  }
  #pie1 {
    width: 100%;
    height: 300px;
  }
  #pie2 {
    width: 100%;
    height: 380px;
  }

  .chartDatabox {
  }
}
</style>
